import axiosInstance from '../utils/requests.js'

// 用户注册
export const register = (username, password) => {
  return axiosInstance.post('/api/user/register/', { username, password })
    .then(response => {
      if (!response.data) throw new Error("响应数据为空");
      if (response.data.code !== 0) {
        throw new Error(response.data.msg || "注册失败");
      }
      return response.data;
    })
    .catch(error => {
      if (error.response) {
        error.message = error.response.data?.msg || '注册失败';
      } else if (error.request) {
        error.message = "网络错误，无法连接服务器";
      }
      throw error;
    });
};

// 用户登录
export const login = async (username, password) => {
  const response = await axiosInstance.post('/api/user/login/', { username, password })
  
  // 提取token和用户信息
  const token = response.data?.data?.token
  const userData = response.data?.data
  
  // 将token设置到axios实例的headers中
  if (token) {
    axiosInstance.defaults.headers.Authorization = `Bearer ${token}`
    // 存储token和用户信息到localStorage
    localStorage.setItem('token', token)
    localStorage.setItem('userType', userData?.user_type || 'user')
    localStorage.setItem('username', userData?.username || '')
  }
  
  return response
}

// 获取用户信息
export const getUserInfo = () => {
  return axiosInstance.get('/api/user/info/')
    .then(response => response.data)
    .catch(error => {
      console.error('获取用户信息失败:', error);
      throw error;
    });
};

// 用户登出
export const logout = () => {
  // 清除axios的token
  delete axiosInstance.defaults.headers.common['Authorization'];
  return Promise.resolve({ code: 0, msg: '登出成功' });
};

/**
 * 获取用户列表 - 仅管理员可访问
 * @returns {Promise} 返回 Promise 对象
 */
export const getUserList = (params = {}) => {
  return axiosInstance.get('/api/user/list/', { params })
    .then(response => response.data)
    .catch(error => {
      console.error('获取用户列表失败:', error);
      throw error;
    });
};

/**
 * 更新用户信息
 * @param {Object} userData 用户数据，包含id、username、password(可选)、userType
 * @returns {Promise} 返回 Promise 对象
 */
export const updateUser = (userData) => {
  const { id, ...data } = userData;
  // 移除空密码
  if (!data.password) {
    delete data.password;
  }
  return axiosInstance.put(`/api/user/update/${id}/`, data)
    .then(response => {
      if (!response.data) throw new Error("响应数据为空");
      if (response.data.code !== 0) {
        throw new Error(response.data.msg || "更新失败");
      }
      return response.data;
    })
    .catch(error => {
      if (error.response) {
        error.message = error.response.data?.msg || '更新失败';
      } else if (error.request) {
        error.message = "网络错误，无法连接服务器";
      }
      throw error;
    });
};

/**
 * 删除用户
 * @param {number} userId 用户ID
 * @returns {Promise} 返回 Promise 对象
 */
export const deleteUser = (userId) => {
  return axiosInstance.delete(`/api/user/delete/${userId}/`)
    .then(response => {
      if (!response.data) throw new Error("响应数据为空");
      if (response.data.code !== 0) {
        throw new Error(response.data.msg || "删除失败");
      }
      return response.data;
    })
    .catch(error => {
      if (error.response) {
        error.message = error.response.data?.msg || '删除失败';
      } else if (error.request) {
        error.message = "网络错误，无法连接服务器";
      }
      throw error;
    });
};

/**
 * 更新当前用户自己的信息
 * @param {Object} userData 用户数据，包含username、password(可选)
 * @returns {Promise} 返回 Promise 对象
 */
export const updateSelfUser = (userData) => {
  const data = { ...userData };
  // 移除空密码
  if (!data.password) {
    delete data.password;
  }
  return axiosInstance.put(`/api/user/self-update/`, data)
    .then(response => {
      if (!response.data) throw new Error("响应数据为空");
      if (response.data.code !== 0) {
        throw new Error(response.data.msg || "更新失败");
      }
      return response.data;
    })
    .catch(error => {
      if (error.response) {
        error.message = error.response.data?.msg || '更新失败';
      } else if (error.request) {
        error.message = "网络错误，无法连接服务器";
      }
      throw error;
    });
};